package hotel.switchs.oversea.online.service.impl;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.MeituanConstants;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.dto.switchs.SwitchOrderInfoDto;
import hotel.base.oversea.entity.SwitchsPoolOrderStateHistory;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.SendUtils;
import hotel.base.oversea.utils.StringUtil;
import hotel.switchs.oversea.api.dto.SwitchCreateRoomDto;
import hotel.switchs.oversea.api.entity.order.SwitchOrderInfo;
import hotel.switchs.oversea.api.entity.order.SwitchOrderPool;
import hotel.switchs.oversea.online.mapper.SwitchOrderPoolMapper;
import hotel.switchs.oversea.online.mapper.SwitchsPoolOrderStateHistoryMapper;
import hotel.switchs.oversea.online.service.SwitchCreateRoomService;
import hotel.switchs.oversea.online.service.SwitchOrderInfoService;
import hotel.switchs.oversea.online.service.SwitchOrderOperateService;
import hotel.switchs.oversea.online.service.SwitchOrderPoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 返回订单信息
 *
 * @author HuangT
 * @date 2020/7/7 20:43
 */
@Slf4j
@Service
public class SwitchOrderOperateServiceImpl implements SwitchOrderOperateService {

    @Resource
    private SwitchOrderPoolService switchOrderPoolService;

    @Resource
    private SwitchsPoolOrderStateHistoryMapper switchsPoolOrderStateHistoryMapper;

    @Resource
    private SwitchOrderInfoService switchOrderInfoService;

    @Resource
    private SwitchCreateRoomService switchCreateRoomService;

    @Resource
    private SwitchOrderPoolMapper switchOrderPoolMapper;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public Result getSwitchOrderInfoByDltAsc() {
        return getOneOrderToFromJob();//获取一条酒店id给下单定时器
    }

    public Result getOneOrderToFromJob(){
        List<SwitchOrderPool> list = switchOrderPoolService.getSwitchOrderInfoForMtAsc();//version 20200828 调整为只取一条 不是取所有
        List<SwitchOrderInfoDto> returnList = new ArrayList<>();
        if(null ==  list || list.size()==0){
            return new Result(JSON.toJSONString(returnList),"success");
        }
        String orderId = list.get(0).getOrderId();

        //vesion qyy  updateOrderResult： 拿单子按照modify_time asc，每次拿出，修改时间，让下一次定时器不会再拿到这笔订单（当这笔订单还来不及被修改状态时），但是还存在一种i情况，当订单就只有一单时，还是会一直被定时器拿到，   //这时候需要缓存做判断
        try{
            SwitchOrderPool switchOrderPoolUpdate = new SwitchOrderPool();
            switchOrderPoolUpdate.setModifyTime(new Date());
            switchOrderPoolUpdate.setId(list.get(0).getId());
            switchOrderPoolService.updateOrderResultNotSaveLog(switchOrderPoolUpdate);
        }catch (Exception e){
            log.error("updateOrderResult 异常 "+list.get(0).getId());
            e.printStackTrace();
        }
        if(list.get(0).getMtOrderState().equals("0")){
            //美团未下单
            try{
                Integer count = switchOrderPoolService.hasMtBooking(orderId);
                if(count>0){
                    //美团已存在下单订单时
                    return new Result("美团已存在下单订单时 当前获取订单返回null，orderId="+orderId,CommonConstants.REQUEST_ERROR);
                }
            }catch (Exception e){
                log.error("switchOrderPoolService.hasMtBooking 异常 "+list.get(0).getId());
                e.printStackTrace();
            }
        }
        if(list.get(0).getSysOrderState()==0 && list.get(0).getMtOrderState().equals("0") && null != redisTemplate.opsForValue().get(MeituanConstants.REDIS_KEY_HEAD_MT_ORDER_JOB_ING_VALUE_ORDER_ID+orderId)){//标识当前订单下单中,如果存在则下一次进来的定时器不处理该订单（存在时间差，上一次还没数据库update，定时器就进来了）//在getAllWaitOrder里set
            /*log.info("getOneOrderToFromJob 每次获取一个可下单订单号：订单还在处理中 订单重复={}",orderId);
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return getOneOrderToFromJob();*/
            return new Result("程序判断当前订单号存在处理中，为订单重复="+orderId,CommonConstants.REQUEST_ERROR);
        }else{
            if(list.get(0).getSysOrderState()==7 || list.get(0).getSysOrderState() == 8){
                redisTemplate.delete(MeituanConstants.REDIS_KEY_HEAD_MT_ORDER_JOB_ING_VALUE_ORDER_ID+orderId);//该订单已完成了下单流程，后续状态流程不涉及下单，删除下单重复标识
            }
            for (SwitchOrderPool switchOrderPool:list){
                //通过订单编号获取订单详情
                SwitchOrderInfo switchOrderInfo = switchOrderInfoService.getDltOrderInfoByDltId(switchOrderPool.getOrderId());
                if(null == switchOrderInfo){
                    //return new Result<>("getDltOrderInfoByDltId 订单详情为空!switchOrderPool="+ JSON.toJSONString(switchOrderPool), CommonConstants.ERROR);
                    log.error("getSwitchOrderInfoByDltA 处理待下单数据，存在详情为空,请人工核实！：scswitchOrderPool={},list={}", JSON.toJSONString(switchOrderPool), JSON.toJSONString(list));
                    SendUtils.dingMsg("处理待下单数据，存在详情为空,请人工核实！","getSwitchOrderInfoByDltAsc："+ JSON.toJSONString(switchOrderPool), MessageEnums.genre.DELAYED_ORDER.getCode(),restTemplate);
                    continue;
                }
                SwitchOrderInfoDto switchOrderInfoDto = new SwitchOrderInfoDto();
                switchOrderInfoDto.setOrderPoolId(switchOrderPool.getId());
                //入住日期
                switchOrderInfoDto.setCheckinDate(DateUtil.switchDateParse(switchOrderInfo.getCheckinDate()));
                //离店日期
                switchOrderInfoDto.setCheckoutDate(DateUtil.switchDateParse(switchOrderInfo.getCheckoutDate()));
                //备注
                switchOrderInfoDto.setComment(switchOrderInfo.getRemark());
                //联系人姓名
                switchOrderInfoDto.setContactName(switchOrderInfo.getContactName());
                //联系人电话
                switchOrderInfoDto.setContactPhone(switchOrderInfo.getCustomerDid());
                //分销商订单号
                switchOrderInfoDto.setDistributorOrderId(switchOrderInfo.getDistributorOrderId());
                //酒店ID
                switchOrderInfoDto.setHotelId(switchOrderInfo.getHotelId());
                //是否需要发票
                switchOrderInfoDto.setNeedInvoice(MeituanConstants.NEED_INVOICE_NO);
                //入住人员列表
                switchOrderInfoDto.setPersonNames(switchOrderInfo.getCustomerName());
                //预订房间数
                switchOrderInfoDto.setRoomnum(switchOrderInfo.getRoomnum());
                //总价
                switchOrderInfoDto.setTotalPrice(switchOrderInfo.getOrderPrice().intValue());//携程单位 元
                //代理通订单ID
                switchOrderInfoDto.setDltOrderId(switchOrderInfo.getDltOrderId());
                //携程房型ID
                switchOrderInfoDto.setRoomId(switchOrderInfo.getRoomId());
                //系统订单状态
                switchOrderInfoDto.setSysOrderState(switchOrderPool.getSysOrderState());
                //是否可立即下单
                switchOrderInfoDto.setIsOrder(switchOrderPool.getIsOrder());
                //订单ID
                switchOrderInfoDto.setOrderId(switchOrderInfo.getOrderId());
                //通过携程房型ID获取美团产品信息
                SwitchCreateRoomDto switchCreateRoomDto = switchCreateRoomService.getMtInfoBySwitchRoomId(Integer.parseInt(switchOrderInfo.getRoomId()));
                if (switchCreateRoomDto == null) {
                    SendUtils.dingMsg("下单定时器获取酒店下单，程序获取美团产品信息异常","switchCreateRoomDto is null ,SwitchOrderOperateServiceImpl 122,orderId="+switchOrderInfo.getOrderId(),MessageEnums.genre.DELAYED_ORDER.getCode(),restTemplate);
                    return new Result<>("获取美团产品信息异常! switchCreateRoomDto is null ", CommonConstants.ERROR);
                }
                switchOrderInfoDto.setGoodsId(switchCreateRoomDto.getMtGoodId());
                switchOrderInfoDto.setMtHotelId(switchCreateRoomDto.getMtHotelId());
                returnList.add(switchOrderInfoDto);
                //标识当前订单下单中,如果存在则下一次进来的定时器不处理该订单（存在时间差，上一次还没数据库update，定时器就进来了）
            }
            return new Result(JSON.toJSONString(returnList),"success");
        }

    }

    @Override
    public Result getSwitchOrderInfoByDltByOrderId(String orderId) {

//        log.info("getSwitchOrderInfoByDltByOrderId===orderId----{}", orderId);
//        //获取可向mt下单的订单编号
//        Example example = new Example(SwitchOrderPool.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("orderId",orderId);
//        example.setOrderByClause(" id limit 1");
//        SwitchOrderPool switchOrderPool = switchOrderPoolMapper.selectOneByExample(example);
//        log.info("getSwitchOrderInfoByDltByOrderId===switchOrderPool----{}", JacksonUtil.objectToJson(switchOrderPool));
//        if (null == switchOrderPool) {
//            return new Result<>("getSwitchOrderInfoForMt 订单池代理通订单ID为空!", CommonConstants.ERROR);
//        }
        log.info("getSwitchOrderInfoByDltByOrderId---orderId---> {}",orderId);
        //通过订单编号获取订单详情
        SwitchOrderInfo switchOrderInfo = switchOrderInfoService.getDltOrderInfoByDltId(orderId);
        if(null == switchOrderInfo){
            return new Result<>("订单详情异常!", CommonConstants.ERROR);
        }
        SwitchOrderInfoDto switchOrderInfoDto = new SwitchOrderInfoDto();
//        switchOrderInfoDto.setOrderPoolId(switchOrderPool.getId());
        //入住日期
        switchOrderInfoDto.setCheckinDate(switchOrderInfo.getCheckinDate());
        //离店日期
        switchOrderInfoDto.setCheckoutDate(switchOrderInfo.getCheckoutDate());
        //备注
        switchOrderInfoDto.setComment(switchOrderInfo.getRemark());
        //联系人姓名
        switchOrderInfoDto.setContactName(switchOrderInfo.getContactName());
        //联系人电话
        switchOrderInfoDto.setContactPhone(switchOrderInfo.getCustomerDid());
        //分销商订单号
        switchOrderInfoDto.setDistributorOrderId(switchOrderInfo.getDistributorOrderId());
        //酒店ID
        switchOrderInfoDto.setHotelId(switchOrderInfo.getHotelId());
        //是否需要发票
        switchOrderInfoDto.setNeedInvoice(MeituanConstants.NEED_INVOICE_NO);
        //入住人员列表
        switchOrderInfoDto.setPersonNames(switchOrderInfo.getCustomerName());
        //预订房间数
        switchOrderInfoDto.setRoomnum(switchOrderInfo.getRoomnum());
        //总价
        switchOrderInfoDto.setTotalPrice(switchOrderInfo.getOrderPrice().intValue());
        //代理通订单ID
        switchOrderInfoDto.setDltOrderId(switchOrderInfo.getDltOrderId());
        //携程房型ID
        switchOrderInfoDto.setRoomId(switchOrderInfo.getRoomId());
////        系统订单状态
//        switchOrderInfoDto.setSysOrderState(switchOrderPool.getSysOrderState());
//        //是否可立即下单
//        switchOrderInfoDto.setIsOrder(switchOrderPool.getIsOrder());
        //通过携程房型ID获取美团产品信息
        SwitchCreateRoomDto switchCreateRoomDto = switchCreateRoomService.getMtInfoBySwitchRoomId(Integer.parseInt(switchOrderInfo.getRoomId()));
        if (switchCreateRoomDto == null) {
            return new Result<>("获取美团产品信息异常!", CommonConstants.ERROR);
        }
        switchOrderInfoDto.setGoodsId(switchCreateRoomDto.getMtGoodId());
        switchOrderInfoDto.setMtHotelId(switchCreateRoomDto.getMtHotelId());
        return new Result<>(switchOrderInfoDto);
    }


    @Override
    public Result updatePoolMtStateByOrderId(String orderId, String mtOrderState, Integer sysOrderState,Integer isOrder,Integer orderWaitTime,String isOrderRemark,String logRemark) {
        SwitchOrderPool switchOrderPool = new SwitchOrderPool();
        switchOrderPool.setOrderId(orderId);
        if (null != mtOrderState) {
            switchOrderPool.setMtOrderState(mtOrderState);
        }
        if (null != sysOrderState) {
            switchOrderPool.setSysOrderState(sysOrderState);
        }
        if (null != isOrder) {
            switchOrderPool.setIsOrder(isOrder);
        }
        if (null != orderWaitTime) {
            switchOrderPool.setOrderWaitTime(orderWaitTime);
        }
        if (null != isOrderRemark) {
            switchOrderPool.setIsOrderRemark(isOrderRemark);
        }
        switchOrderPool.setModifyTime(new Date());
        Example example = new Example(SwitchOrderPool.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        switchOrderPoolMapper.updateByExampleSelective(switchOrderPool, example);

        this.insertPoolStateHistroy(switchOrderPool.getOrderId(),switchOrderPool.getSysOrderState(),
                switchOrderPool.getMtOrderState(),switchOrderPool.getIsOrder(),logRemark);

        return new Result();
    }

    public void insertPoolStateHistroy(String orderId,Integer sysState,String mtState,Integer isOrder,String remark){
        SwitchsPoolOrderStateHistory switchsPoolOrderStateHistory = new SwitchsPoolOrderStateHistory();
        switchsPoolOrderStateHistory.setId(StringUtil.getUUID());
        switchsPoolOrderStateHistory.setOrderId(orderId);
        switchsPoolOrderStateHistory.setCreateTime(new Date());
        switchsPoolOrderStateHistory.setIsOrder(isOrder);
        switchsPoolOrderStateHistory.setSysStatus(sysState);
        switchsPoolOrderStateHistory.setMtStatus(mtState==null?null:Integer.valueOf(mtState));
        switchsPoolOrderStateHistory.setRemark(remark);
        try{
            switchsPoolOrderStateHistoryMapper.insert(switchsPoolOrderStateHistory);
        }catch (Exception e){
            log.error("switchsPoolOrderStateHistoryMapper 保存异常："+e.getMessage());
            e.printStackTrace();
        }
    }
}
